"""
扫货记录页面
"""
from PyQt6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QTableWidget,
                           QTableWidgetItem, QPushButton, QLineEdit, QLabel,
                           QHeaderView, QFrame, QStyle, QStyledItemDelegate)
from PyQt6.QtCore import Qt, QUrl
from PyQt6.QtGui import QColor, QDesktopServices
from com.db.order_record_manager import OrderRecordManager
from gui.styles.table_style import apply_default_table_style, set_columns_stretch
from gui.styles.pagination_style import PaginationWidget
from datetime import datetime

class HyperlinkDelegate(QStyledItemDelegate):
    """超链接样式代理"""
    def __init__(self, parent=None):
        super().__init__(parent)
        self.hover_row = -1
        
    def createEditor(self, parent, option, index):
        return None
        
    def paint(self, painter, option, index):
        if option.state & QStyle.StateFlag.State_MouseOver:
            # 鼠标悬停时显示下划线
            option.font.setUnderline(True)
            
        if index.column() == 3:  # 商品名称列
            option.palette.setColor(option.palette.ColorRole.Text, QColor('#409EFF'))
            
        super().paint(painter, option, index)

class ScanRecordPage(QWidget):
    """扫货记录页面"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.record_manager = OrderRecordManager()
        self.setup_ui()
        self.load_records()  # 从数据库加载记录数据
        self.setup_connections()  # 设置信号连接
    
    def setup_ui(self):
        """初始化UI"""
        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)  # 移除边距，使表格占满整个空间
        layout.setSpacing(0)  # 减少间距
        
        # 搜索区域
        search_frame = QFrame()
        search_frame.setStyleSheet("""
            QFrame {
                background-color: white;
                border: none;
                border-bottom: 1px solid #ebeef5;
            }
        """)
        search_layout = QHBoxLayout(search_frame)
        search_layout.setContentsMargins(15, 10, 15, 10)
        
        # 左侧搜索区域
        left_widget = QWidget()
        left_layout = QHBoxLayout(left_widget)
        left_layout.setContentsMargins(0, 0, 0, 0)
        left_layout.setSpacing(10)
        
        # 搜索输入框
        self.search_input = QLineEdit()
        self.search_input.setPlaceholderText("输入商品名称搜索")
        self.search_input.setStyleSheet("""
            QLineEdit {
                padding: 5px 10px;
                border: 1px solid #dcdfe6;
                border-radius: 2px;
                font-size: 12px;
                color: #606266;
                min-width: 200px;
            }
            QLineEdit:focus {
                border-color: #409eff;
            }
        """)
        
        # 搜索按钮
        search_btn = QPushButton("搜索")
        search_btn.setObjectName("搜索")  # 设置对象名称
        search_btn.setStyleSheet("""
            QPushButton {
                padding: 5px 15px;
                background-color: #409eff;
                color: white;
                border: none;
                border-radius: 2px;
                font-size: 12px;
                min-width: 60px;
            }
            QPushButton:hover {
                background-color: #66b1ff;
            }
        """)
        
        # 重置按钮
        reset_btn = QPushButton("重置")
        reset_btn.setObjectName("重置")  # 设置对象名称
        reset_btn.setStyleSheet("""
            QPushButton {
                padding: 5px 15px;
                background-color: white;
                color: #606266;
                border: 1px solid #dcdfe6;
                border-radius: 2px;
                font-size: 12px;
                min-width: 60px;
            }
            QPushButton:hover {
                color: #409eff;
                border-color: #c6e2ff;
                background-color: #ecf5ff;
            }
        """)
        
        left_layout.addWidget(self.search_input)
        left_layout.addWidget(search_btn)
        left_layout.addWidget(reset_btn)
        
        # 将左侧添加到主布局
        search_layout.addWidget(left_widget)
        search_layout.addStretch()
        
        # 表格
        self.table = QTableWidget()
        apply_default_table_style(self.table)
        
        # 禁用编辑
        self.table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
        
        # 设置超链接代理
        self.hyperlink_delegate = HyperlinkDelegate(self.table)
        self.table.setItemDelegateForColumn(3, self.hyperlink_delegate)  # 为商品名称列设置代理
        
        # 设置表格列
        headers = ["下单号", "账号", "商品ID", "商品名称", "价格", "磨损", "购买状态", "报价状态", "报价失败原因", "下单时间"]
        self.table.setColumnCount(len(headers))
        self.table.setHorizontalHeaderLabels(headers)
        
        # 设置表格列宽
        set_columns_stretch(self.table)
        
        # 分页控件
        self.pagination = PaginationWidget()
        self.pagination.prev_btn.clicked.connect(self.on_prev_page)
        self.pagination.next_btn.clicked.connect(self.on_next_page)
        self.pagination.page_size_spin.valueChanged.connect(self.on_page_size_changed)
        
        # 添加到主布局
        layout.addWidget(search_frame)
        layout.addWidget(self.table)
        layout.addWidget(self.pagination)
    
    def load_records(self, keyword=None):
        """从数据库加载记录数据"""
        # 获取当前页数据
        page = self.pagination.page
        page_size = self.pagination.page_size
        offset = (page - 1) * page_size

        # 获取总记录数和记录
        total_count = self.record_manager.get_record_count(keyword)
        
        # 获取分页数据
        records = self.record_manager.search_records(
            keyword=keyword,
            limit=page_size,
            offset=offset
        )
        
        # 更新分页状态
        self.pagination.update_state(page, total_count, page_size)
        
        # 更新表格
        self.table.setRowCount(len(records))
        
        # 购买状态映射 (0：失败 1：等待支付 2：支付成功)
        buy_status_map = {
            0: "支付失败",
            1: "等待支付",
            2: "支付成功"
        }
        
        # 报价状态映射 (0：失败 1：等待报价 2：报价成功)
        offer_status_map = {
            0: "报价失败",
            1: "等待报价",
            2: "报价成功"
        }
        
        for row, record in enumerate(records):
            # 下单号
            self.table.setItem(row, 0, QTableWidgetItem(str(record.get('order_no', ''))))
            # 账号
            self.table.setItem(row, 1, QTableWidgetItem(str(record.get('account_name', ''))))
            # 商品ID
            self.table.setItem(row, 2, QTableWidgetItem(str(record.get('goods_id', ''))))
            # 商品名称 - 使用task_name
            name_item = QTableWidgetItem(str(record.get('task_name', '')))
            self.table.setItem(row, 3, name_item)
            # 价格
            self.table.setItem(row, 4, QTableWidgetItem(str(record.get('price', ''))))
            # 磨损
            paintwear = record.get('paintwear')
            if paintwear is not None:
                try:
                    paintwear = f"{float(paintwear):.4f}"  # 保留4位小数
                except (ValueError, TypeError):
                    paintwear = str(paintwear)
            else:
                paintwear = ''
            self.table.setItem(row, 5, QTableWidgetItem(paintwear))
            
            # 购买状态
            buy_status = record.get('buy_status')
            buy_status_text = buy_status_map.get(buy_status, "未知状态")
            buy_status_item = QTableWidgetItem(buy_status_text)
            
            # 设置状态颜色
            if buy_status == 2:  # 成功
                buy_status_item.setForeground(QColor('#67C23A'))
            elif buy_status == 0:  # 失败
                buy_status_item.setForeground(QColor('#F56C6C'))
            else:  # 等待中
                buy_status_item.setForeground(QColor('#E6A23C'))
            
            self.table.setItem(row, 6, buy_status_item)
            
            # 报价状态
            offer_status = record.get('offer_status')
            offer_status_text = offer_status_map.get(offer_status, "未知状态")
            offer_status_item = QTableWidgetItem(offer_status_text)
            
            # 设置状态颜色
            if offer_status == 2:  # 成功
                offer_status_item.setForeground(QColor('#67C23A'))
            elif offer_status == 0:  # 失败
                offer_status_item.setForeground(QColor('#F56C6C'))
            else:  # 等待中
                offer_status_item.setForeground(QColor('#E6A23C'))
                
            self.table.setItem(row, 7, offer_status_item)
            
            # 报价失败原因
            fail_desc = record.get('offer_fail_desc', '')
            self.table.setItem(row, 8, QTableWidgetItem(str(fail_desc)))
            
            # 下单时间
            create_at = record.get('create_at', '')
            if create_at:
                try:
                    if isinstance(create_at, str):
                        dt = datetime.fromisoformat(create_at.replace('Z', '+00:00'))
                        create_at = dt.strftime('%Y-%m-%d %H:%M:%S')
                except (ValueError, TypeError):
                    pass
            self.table.setItem(row, 9, QTableWidgetItem(str(create_at)))
            
            # 根据状态设置颜色
            for col in range(self.table.columnCount()):
                item = self.table.item(row, col)
                if item:
                    item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
                    
    def on_prev_page(self):
        """上一页"""
        if self.pagination.page > 1:
            self.pagination.page -= 1
            self.load_records()
    
    def on_next_page(self):
        """下一页"""
        self.pagination.page += 1
        self.load_records()
    
    def on_page_size_changed(self, value):
        """页面大小改变"""
        self.pagination.page_size = value
        self.pagination.page = 1
        self.load_records()
    
    def on_search(self):
        """搜索处理"""
        # 获取搜索关键词
        keyword = self.search_input.text().strip()
        # 重置到第一页
        self.pagination.page = 1
        # 加载搜索结果
        self.load_records(keyword)
        
    def on_reset(self):
        """重置处理"""
        # 清空搜索框
        self.search_input.clear()
        # 重置分页到第一页
        self.pagination.page = 1
        # 重新加载记录
        self.load_records()
    
    def setup_connections(self):
        """设置信号连接"""
        # 表格点击事件
        self.table.cellClicked.connect(self.on_table_cell_clicked)
        
        # 搜索按钮点击事件
        search_btn = self.findChild(QPushButton, "搜索")
        if search_btn:
            search_btn.clicked.connect(self.on_search)
            
        # 重置按钮点击事件
        reset_btn = self.findChild(QPushButton, "重置")
        if reset_btn:
            reset_btn.clicked.connect(self.on_reset)
            
    def on_table_cell_clicked(self, row, column):
        """处理表格单元格点击事件"""
        if column == 3:  # 商品名称列
            item = self.table.item(row, column)
            if item:
                # 获取商品ID
                goods_id_item = self.table.item(row, 2)  # 商品ID在第3列
                if goods_id_item:
                    goods_id = goods_id_item.text()
                    # 构建URL并在浏览器中打开
                    url = f"https://www.youpin898.com/market/goods-list?listType=10&templateId={goods_id}&gameId=730"
                    QDesktopServices.openUrl(QUrl(url))
